//
//  HMEmoticonKeyBoard.swift
//  Weibo
//
//  Created by 黄亦寒 on 2016/10/6.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
//自定义表情键盘
/*
 分为三部分：1.表情视图
           2.页数指示器
           3.toolBar
 */
class HMEmoticonKeyBoard: UIView {

    //页数指示器
    fileprivate lazy var pageControl:UIPageControl = {
       let control = UIPageControl()
        //当前选中的页数的颜色
        control.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named:"compose_keyboard_dot_selected")!)
        //默认页数的颜色
        control.pageIndicatorTintColor = UIColor(patternImage: UIImage(named:"compose_keyboard_dot_normal")!)
        //隐藏单页
        control.hidesForSinglePage = true
        return control
    }()
    
    //toolBar
    fileprivate lazy var toolBar:HMEmoticonToolBar = HMEmoticonToolBar()
    
    //表情视图
    fileprivate lazy var emoticonCollectionView:UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
       let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
        view.backgroundColor = self.backgroundColor
        //设置数据源
         view.dataSource = self
        //设置代理
        view.delegate = self
        //设置滚动方向
        flowLayout.scrollDirection = .horizontal
        //开启分页
        view.isPagingEnabled = true
        //隐藏水平方向和垂直方向的滚动条
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        //取消弹簧效果
        view.bounces = false
        //注册cell
        view.register(HMEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setUpUI() {
        backgroundColor = UIColor(patternImage: UIImage(named:"emoticon_keyboard_background")!)
        //设置默认滚动到的indexPath
        let normalIndexPath = IndexPath(item: 0, section: 1)
        //等待其他视图初始化和绑定数据完成后再滚动到指定的indexPath
        DispatchQueue.main.async {
            self.emoticonCollectionView.scrollToItem(at: normalIndexPath, at: .left, animated: false)
        }
        
        //获取默认page的数据
        self.setPageControlData(indexPath: normalIndexPath)
        
        addSubview(toolBar)
        addSubview(emoticonCollectionView)
        addSubview(pageControl)
        //设置控件约束
        emoticonCollectionView.snp_makeConstraints { (make) in
            make.top.left.right.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        pageControl.snp_makeConstraints { (make) in
            make.bottom.equalTo(emoticonCollectionView)
            make.centerX.equalTo(emoticonCollectionView)
            make.height.equalTo(10)
        }
        
        toolBar.snp_makeConstraints { (make) in
            make.bottom.left.right.equalTo(self)
            make.height.equalTo(35)
        }
        
        toolBar.callBack = { [weak self] (type:HMEmoticonToolBarButtonType) in
            let indexPath:IndexPath
            
            switch type {
            case .recent:
                print("最近")
                indexPath = IndexPath(item: 0, section: 0)
            case .normal:
                print("默认")
                indexPath = IndexPath(item: 0, section: 1)
            case .emoji:
                print("Emoji")
                indexPath = IndexPath(item: 0, section: 2)
            case .lxh:
                print("浪小花")
                indexPath = IndexPath(item: 0, section: 3)
            }
            //把collectionView滚动到指定的indexPath上
            self?.emoticonCollectionView.scrollToItem(at: indexPath, at: .left, animated: false)
            self?.setPageControlData(indexPath: indexPath)
        }
    }
    
    //设置表情视图每个cell的大小
    override func layoutSubviews() {
        super.layoutSubviews()
        //获取布局方式
        let flowLayout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        //cell的大小
        flowLayout.itemSize = emoticonCollectionView.size
        //设置垂直间距和水平间距
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        
    }
    
    //刷新最近表情数据的方法
    func reloadRecentData() {
        let indexPath = IndexPath(item: 0, section: 0)
        
        emoticonCollectionView.reloadItems(at: [indexPath])
        
    }
    
}

//数据源方法
extension HMEmoticonKeyBoard:UICollectionViewDataSource,UICollectionViewDelegate {
    //组数
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return HMEmoticonTools.sharedTools.allEmoticonsArray.count
    }
    //每组对应的页数
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HMEmoticonTools.sharedTools.allEmoticonsArray[section].count
    }
    //创建cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HMEmoticonCollectionViewCell
        cell.indexPath = indexPath
        cell.emoticonArray = HMEmoticonTools.sharedTools.allEmoticonsArray[indexPath.section][indexPath.item]
        //cell.backgroundColor = RandomColor()
        
        return cell
        
    }
    
    //监听collectionView的滚动
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //获取表情视图的中心点
        let centerX = scrollView.contentOffset.x + emoticonCollectionView.width / 2
        let centerY = scrollView.contentOffset.y + emoticonCollectionView.height / 2
        
        //获取中心点
        let center = CGPoint(x: centerX, y: centerY)
        //通过中心点获取对应的cell的indexPath
        if let indexPath = emoticonCollectionView.indexPathForItem(at: center) {
            let section = indexPath.section
            print(section)
            
            //通过section选中对应的toolBar按钮
            toolBar.selectedButton(section: section)
            setPageControlData(indexPath: indexPath)
        }
  
    }
    
    //通过indexPath绑定pageControl数据
    func setPageControlData(indexPath:IndexPath) {
        pageControl.numberOfPages = HMEmoticonTools.sharedTools.allEmoticonsArray[indexPath.section].count
        pageControl.currentPage = indexPath.item
    }
}
